package com.ktjy.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjy.entity.SysRole;
import com.ktjy.entity.SysUser;
import com.ktjy.service.SysRoleService;
import com.ktjy.service.SysUserService;
import com.ktjy.utils.Constants;
import com.ktjy.utils.Page;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/main/user")
public class SysUserController extends BaseController{
    Logger logger= LoggerFactory.getLogger(SysUserController.class);

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRoleService sysRoleService;

    @RequestMapping("/page")
    public String page(SysUser sysUser,
                       @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
                       Model model){
        try {
            //分页查询用户信息
            Page<SysUser> page = sysUserService.findPage(sysUser, pageNo, pageSize);
            model.addAttribute("pageInfo",page);

            //查询所有角色
            List<SysRole> roleList = sysRoleService.findAll();
            model.addAttribute("roleList",roleList);

            //查询条件回显
            model.addAttribute("condition",sysUser);

        } catch (Exception e) {
            logger.error("SysUserController 中的 page 方法执行发生错误。{} ",e);
            throw new RuntimeException(e);
        }
        return "user/page";
    }

    /**
     * 跳转到新增页面
     * @return
     */
    @GetMapping("/save")
    public String toSave(Model model){
        //查询所有角色
        List<SysRole> roleList = sysRoleService.findAll();
        model.addAttribute("roleList",roleList);
        return "user/save";
    }

    @PostMapping("/save")
    public String doSave(SysUser sysUser,
                         HttpServletRequest request,
                         HttpSession session,
                         @RequestParam("idPic") MultipartFile idPic,
                         @RequestParam("workPic") MultipartFile workPic){
        // 设置保存路径
        String uploadPath="/statics/upload/";
        String rootPath=request.getServletContext().getRealPath(uploadPath);
        try {
            //1.jpg  //wyewueywueywuyeuwy343434.jpg
            if(idPic !=null && !idPic.isEmpty()){
                //UUID
                //1. 重命名文件
                //获取源文件后缀名
                String fileName=idPic.getOriginalFilename();
                //获取文件名的后缀
                String extension=StringUtils.getFilenameExtension(fileName);
                //使用uuid生成文件名称
                String uploadFileName= UUID.randomUUID()+"."+extension;

                //2.判断要保存的目录是否存在
                File file=new File(rootPath,uploadFileName);
                if(!file.getParentFile().exists()){
                    file.getParentFile().mkdirs();
                }
                //3.保存
                idPic.transferTo(file);

                //设置文件路劲
                sysUser.setIdPicPath(uploadPath+uploadFileName);
            }

            if(workPic !=null && !workPic.isEmpty()){
                //UUID
                //1. 重命名文件
                //获取源文件后缀名
                String fileName=workPic.getOriginalFilename();
                //获取文件名的后缀
                String extension=StringUtils.getFilenameExtension(fileName);
                //使用uuid生成文件名称
                String uploadFileName= UUID.randomUUID()+"."+extension;

                //2.判断要保存的目录是否存在
                File file=new File(rootPath,uploadFileName);
                if(!file.getParentFile().exists()){
                    file.getParentFile().mkdirs();
                }
                //3.保存
                workPic.transferTo(file);

                //设置文件路劲
                sysUser.setWorkPicPath(uploadPath+uploadFileName);
            }

            SysUser loginUser= (SysUser)session.getAttribute(Constants.SESSION_USER);
            sysUser.setCreatedUserId(loginUser.getId());
            sysUser.setCreatedTime(new Date());

            boolean ok =false;
            if(sysUser.getId()==null){//新增
                 ok = sysUserService.save(sysUser);
            }else{//修改
                 ok=sysUserService.update(sysUser);
            }

            if(ok){
                //跳转到列表;重定向到分页方法
                return redirect("/main/user/page");
            }else{
                //跳回新增页面
                return "user/save";
            }
        } catch (Exception e) {
            logger.error("SysUserController 中的 save 方法执行发生错误。{} ",e);
            throw new RuntimeException(e);
        }
    }

    //rest风格通俗理解 是一种定义请求路劲的方式，他可以直接在路劲上传递参数
    //跟传统的请求路劲的区别
    //路劲?参数名=参数值   vs  路劲/参数名

//    @GetMapping("/view/{id}")
//    public String view(@PathVariable("id") Long id,Model model){
//        try {
//            SysUser sysUser = sysUserService.findById(id);
//            model.addAttribute("sysUser",sysUser);
//        } catch (Exception e) {
//            logger.error("SysUserController 中的 view 方法执行发生错误。{} ",e);
//            throw new RuntimeException(e);
//        }
//        return "user/view";
//    }

    @GetMapping("/{id}/view")
    @ResponseBody
    public Object view(@PathVariable("id") Long id){
        Map<String,Object> map=new HashMap<>();
        try {
            SysUser sysUser = sysUserService.findById(id);
            if(sysUser!=null){
                map.put("code",200);
                map.put("data",sysUser);
            }else{
                map.put("code",500);
            }
        } catch (Exception e) {
            logger.error("SysUserController 中的 view 方法执行发生错误。{} ",e);
            map.put("code",500);
        }
        return map;
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id,Model model){
        try {
            SysUser sysUser = sysUserService.findById(id);
            model.addAttribute("sysUser",sysUser);

            //查询所有角色
            List<SysRole> roleList = sysRoleService.findAll();
            model.addAttribute("roleList",roleList);
        } catch (Exception e) {
            logger.error("SysUserController 中的 toEdit 方法执行发生错误。{} ",e);
            throw new RuntimeException(e);
        }

        return "user/save";
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Long id){
        Map<String,Object> map=new HashMap<>();
        try {
            boolean ok = sysUserService.delete(id);  //调用service的方法进行数据删除
            if(ok){
                map.put("code",200);
                map.put("msg","删除成功");
            }else{
                map.put("code",500);
                map.put("msg","删除失败");
            }
        } catch (Exception e) {
            logger.error("SysUserController 中的 del 方法执行发生错误。{} ",e);
            map.put("code",500);
            map.put("msg","删除失败");
        }
        return map;
    }

    @GetMapping("/accountExist")
    @ResponseBody
    public Object accountExist(@RequestParam("account") String account){
        Map<String,Object> map=new HashMap<>();
        try {
            SysUser sysUser = sysUserService.findByAccount(account);  //调用service的方法进行数据删除
            if(sysUser!=null){
                map.put("exist",1);
            }else{
                map.put("exist",0);
            }
        } catch (Exception e) {
            logger.error("SysUserController 中的 accountExist 方法执行发生错误。{} ",e);
            map.put("exist",-1);
            map.put("error","系统繁忙，请稍后再试");
        }
        return map;
    }

}
